<?php

namespace App\Http\Controllers\admin;

use App\Events\Application as EventsApplication;
use App\Http\Controllers\Controller;
use App\Models\Application;
use App\Models\ApplicationProcesses;
use App\Services\ApproveService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ApproveController extends Controller
{
    protected $ApproveService;
    public function __construct(ApproveService $ApproveService)
    {
        $this->ApproveService = $ApproveService;
    }

    public function index(Request $Request) {
        $source = $Request->source;
        $model = $Request->model;
        $status = $Request->status;
        $limit = $Request->limit ?: 10;
        $page = $Request->page ?: 1;
        $page = $page * $limit - $limit;

        $sql = $this->ApproveService->get($model,$status);
        if($source){
            $sql->where('source',$Request->source);
        }

        //如果没到就不显示
        $user = Auth::user();
        if($user->id != 1){
            $sql->where('reviewer_id',$user->id);
        }
        $total = $sql->count();
        $data = $sql->skip($page)->take($limit)->orderBy('created_at','desc')->get();
        return response()->json(['code' => '200', 'msg' => '操作成功','total'=>$total,'data'=>$data]);
    }

    public function wait(Request $Request) {
        $typePayData = [
            ['title'=>'甲方开票','id'=>'ProjectInvoice','source'=>'ProjectInvoice','value'=>0],
            ['title'=>'材料付款','id'=>'MaterialPay','source'=>'MaterialPay','value'=>0],
            ['title'=>'施工班组付款','id'=>'LaborPay','source'=>'LaborPay','value'=>0],
            ['title'=>'报销','id'=>'Reimburse','source'=>'Reimburse','value'=>0],
            ['title'=>'备用金','id'=>'Imprest','source'=>'Imprest','value'=>0],
        ];

        $typeData = [
            // ['title'=>'材料采购','id'=>'Material','value'=>0],
            ['title'=>'材料合同','id'=>'Contract','source'=>'Material','value'=>0],
            // ['title'=>'施工班组','id'=>'Labor','value'=>0],
            ['title'=>'施工班组合同','id'=>'Contract','source'=>'Labor','value'=>0],
            ['title'=>'资料下载申请','id'=>'Down','source'=>'Down','value'=>0],
            ['title'=>'用章申请','id'=>'Stamp','source'=>'Stamp','value'=>0],
            ['title'=>'工期重难点措施','id'=>'Difficulty','source'=>'Difficulty','value'=>0],
            ['title'=>'资金,法律风险措施','id'=>'Risk','source'=>'Risk','value'=>0],
            ['title'=>'施工日记','id'=>'Diary','source'=>'Diary','value'=>0],
            ['title'=>'请假申请','id'=>'Leave','source'=>'Leave','value'=>0],
            ['title'=>'通用报告申请','id'=>'Other','source'=>'Other','value'=>0],
            ['title'=>'入库申请','id'=>'WarehousesIn','source'=>'WarehousesIn','value'=>0],
            ['title'=>'出库申请','id'=>'WarehousesOut','source'=>'WarehousesOut','value'=>0],

        ];

        $deleteData = [
            ['title'=>'供应商删除','id'=>'Supplier','source'=>'Supplier','value'=>0],
            ['title'=>'班组商删除','id'=>'Team','source'=>'Team','value'=>0],
        ];

        $data = Application::where('status','pending')->where('reviewer_id',Auth::user()->id)->get();
        $total = 0;
        foreach ($data as $k => $v) {
            foreach ($typeData as $key => $value) {
                if($value['id'] == $v->model && $value['source'] == $v->source){
                    $typeData[$key]['value'] ++;
                    $total ++;
                }
            }

            foreach ($typePayData as $kp => $vp) {
                if($vp['id'] == $v->model){
                    $typePayData[$kp]['value'] ++;
                    $total ++;
                }
            }

            foreach ($deleteData as $kp => $vp) {
                if($vp['id'] == $v->model){
                    $deleteData[$kp]['value'] ++;
                    $total ++;
                }
            }
        }

        return response()->json(['code' => '200', 'msg' => '操作成功','total'=>$total,'typeData'=>$typeData,'deleteData'=>$deleteData,'typePayData'=>$typePayData]);
    }

    public function sources(Request $Request) {
        $source = $Request->source;
        $model = $Request->model;
        $status = $Request->status;
        $limit = $Request->limit ?: 10;
        $page = $Request->page ?: 1;
        $page = $page * $limit - $limit;

        $sql = $this->ApproveService->getSource($source,$model,$status);
        $sql->where('project_id',$Request->project_id);
        $total = $sql->count();
        $data = $sql->skip($page)->take($limit)->orderBy('created_at','desc')->get();
        return response()->json(['code' => '200', 'msg' => '操作成功','total'=>$total,'data'=>$data]);
    }

    public function records(Request $Request) {

        $data = $this->ApproveService->records($Request->id);
        return response()->json(['code' => '200', 'msg' => '操作成功','data'=>$data]);
    }

    public function costs(Request $Request) {
        $data = $this->ApproveService->costs($Request->model,$Request->project_id);
        return response()->json(['code' => '200', 'msg' => '操作成功','data'=>$data]);
    }

    public function show(Request $Request) {
        if(!$Request->id){
            return response()->json(['code' => '403', 'msg' => '参数错误']);
        }
        $data = Application::with('user')->with('records')->where('id',$Request->id)->first();
        //判断是否审批过了
        $file_arr = [];
        if($data->model == 'Reimburse'){
            $r = $data->Reimburse;
            if($r){
                foreach ($r->details as $k => $v) {
                    $file_arr[] = $v['invoice'];
                }
            }
        }
        $data->is_review = false;
        if($data->status == 'approved'){
            $data->is_review = true;
        }
        if($data->status == 'rejected'){
            $data->is_review = true;
        }
        $record = '';
        foreach ($data->records as $k => $v) {
            if($v->reviewer_id == Auth::user()->id && $v->status != 'pending'){
                $data->is_review = true;
                $record = $v;
            }else{
                $data->is_review = false;
                $record = $v;
            }
        }
        if($record){
            $data->status = $record->status;
            $data->comment = $record->comment;
        }
        return response()->json(['code' => '200', 'msg' => '操作成功','data'=>$data,'record'=>$record,'file_arr' => $file_arr]);
    }

    public function store(Request $Request)
    {
        if(!$Request->source_id){
            return response()->json(['code' => '404', 'msg' => '请选择要操作的记录']);
        }
        if(!$Request->type){
            return response()->json(['code' => '404', 'msg' => '申请类别错误']);
        }
        if(!$Request->model){
            return response()->json(['code' => '404', 'msg' => '申请来源错误']);
        }
        // if(!$Request->reason){
        //     return response()->json(['code' => '404', 'msg' => '请输入申请原因']);
        // }
        if(!$Request->project_id){
            $Request->project_id = 9;
        }
        $reason = $Request->reason ?? '/';
        $ApplicationProcesses = ApplicationProcesses::where('project_id',$Request->project_id)->first();
        if(empty($ApplicationProcesses)){
            return response()->json(['code' => '500', 'msg' => '未设置审批流程']);
        }
        //判断是否申请过
        $is = Application::where('source_id',$Request->source_id)->where('model',$Request->model)->where('type',$Request->type)->where('user_id',Auth::user()->id)->where('project_id',$Request->project_id)->orderBy('id','desc')->first();
        if($is){
            if($is->status == 'pending'){
                return response()->json(['code' => '404', 'msg' => '正在审批中，请勿重复申请']);
            }
            // if($is->status == 'rejected'){
            //     return response()->json(['code' => '404', 'msg' => '已经驳回，请勿重复申请']);
            // }
            if($is->status == 'approved'){
                return response()->json(['code' => '404', 'msg' => '已经通过，请勿重复申请']);
            }
        }
        EventsApplication::dispatch($Request->type,$Request->source,$Request->model,Auth::user()->id,$Request->source_id,$Request->project_id,$reason,$Request->payment_type,$Request->pay_info,$Request->price);
        return response()->json(['code' => '200', 'msg' => '操作成功']);
    }

    public function review(Request $Request)
    {
        if(!$Request->application_id){
            return response()->json(['code' => '404', 'msg' => '请选择要操作的记录']);
        }
        //查询当前用户权限
        // $p_u = ProjectUser::where('project_id',$Request->project_id)->where('user_id',Auth::user()->id)->first();
        // $r_u = RoleUser::where('project_id',$Request->project_id)->where('user_id',Auth::user()->id)->first();
        $Application = Application::find($Request->application_id);
        $is = ApplicationProcesses::where('project_id',$Application->project_id)->where('user_id',Auth::user()->id)->first();
        if(!$is){
            return response()->json(['code' => '404', 'msg' => '您没有权限审批']);
        }
        $input = [];
        $input['role_id'] = $is->role_id;
        $input['application_id'] = $Request->application_id;
        $input['comment'] = $Request->comment;
        $input['status'] = $Request->status;
        $input['invoice_type'] = $Request->invoice_type;
        $input['invoice_numbers'] = $Request->invoice_numbers;
        $input['invoice_file'] = $Request->invoice_file;
        $input['receipt'] = $Request->receipt;
        $input['pay_date'] = $Request->pay_date;
        $input['reviewer_id'] = Auth::user()->id;
        $data = $this->ApproveService->review($input,$Request->type);
        return response()->json(['code' => '200', 'msg' => '操作成功','data'=>$data]);
    }

    public function revoke(Request $Request)
    {
        if(!$Request->source_id){
            return response()->json(['code' => '404', 'msg' => '请选择要操作的记录']);
        }

        if(!$Request->model){
            return response()->json(['code' => '404', 'msg' => '申请来源错误']);
        }
        $data = $this->ApproveService->revoke($Request->source_id,$Request->model,$Request->project_id);
        return response()->json(['code' => '200', 'msg' => '操作成功','data' => $data]);
    }


}
